<template>
	<view>
		<view class="form-box">
			<view class="handCenter">
				<canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
					@touchmove="uploadScaleMove" canvas-id="handWriting"></canvas>
			</view>
			<view class="flexWrap">
				<view class="tips">请签署清晰的姓名</view>
				<view class="clear" @tap="retDraw()">清除</view>
			</view>
		</view>
		<view class="bottom-box">
			<view class="bottom-btn" @tap="subCanvas()">
				确认提交
			</view>
		</view>
	</view>
</template>

<script>
	// import base from '@/common/base.js'
	export default {
		data() {
			return {
				canvasName: 'handWriting',
				ctx: '',
				startX: null,
				startY: null,
				canvasWidth: 0,
				canvasHeight: 0,
				selectColor: 'black',
				lineColor: '#1A1A1A', // 颜色
				lineSize: 3, // 笔记倍数
				signImage: '',
				payInfo: {},
				isEmpty: true,
				storeId: "",
				holderOrderId: "",
				name: "",
				idCar: "",
				address: "",
				imageBase64: "",
				isSign:false,
			};
		},
		onLoad(ops) {
			this.holderOrderId = ops.holderOrderId
			this.storeId = ops.storeId
			console.log('ops:',ops)
			this.ctx = uni.createCanvasContext("handWriting");
			this.$nextTick(() => {
				uni.createSelectorQuery().select('.handCenter').boundingClientRect(rect => {
						this.canvasWidth = rect.width;
						this.canvasHeight = rect.height;
					})
					.exec();
			});
		},
		onUnload() {
			if(!this.isSign){
				console.log('未签字取消')
				this.cancellationPay();
			}
		},
		methods: {
			// 取消订单
			cancellationPay() {
				this.$request.post(this.$api.cancellationPay, {
					userId: uni.getStorageSync('userId'),
					holderOrderId: this.holderOrderId
				}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
					}
				})
			},
			// 笔迹开始
			uploadScaleStart(e) {
				this.startX = e.changedTouches[0].x
				this.startY = e.changedTouches[0].y
				//设置画笔参数
				//画笔颜色
				this.ctx.setStrokeStyle(this.lineColor)
				//设置线条粗细
				this.ctx.setLineWidth(this.lineSize)
				//设置线条的结束端点样式
				this.ctx.setLineCap("round") //'butt'、'round'、'square'
				//开始画笔
				this.ctx.beginPath()
			},
			// 笔迹移动
			uploadScaleMove(e) {
				//取点
				let temX = e.changedTouches[0].x
				let temY = e.changedTouches[0].y
				//画线条
				this.ctx.moveTo(this.startX, this.startY)
				this.ctx.lineTo(temX, temY)
				this.ctx.stroke()
				this.startX = temX
				this.startY = temY
				this.ctx.draw(true)
				this.isEmpty = false
				console.log('移动')
			},
			/**
			 * 重写
			 */
			retDraw() {
				this.ctx.clearRect(0, 0, 700, 730);
				this.ctx.draw();
				this.isEmpty = true
			},
			/**
			 * @param {Object} str
			 * @param {Object} color
			 * 选择颜色
			 */
			selectColorEvent(str, color) {
				this.selectColor = str;
				this.lineColor = color;
			},
			//完成
			subCanvas() {
				if (this.isEmpty) {
					this.$tools.showToast('请完成签名');
					return;
				}
				let that=this
				uni.canvasToTempFilePath({
					canvasId: 'handWriting',
					fileType: 'png',
					quality: 1, //图片质量
					success(res) {
						// 获取临时文件路径
						let tempFilePath = res.tempFilePath;
						// 使用uni.getFileSystemManager获取文件内容
						let fileManager = uni.getFileSystemManager();
						fileManager.readFile({
							filePath: tempFilePath,
							encoding: 'base64',
							success: function(data) {
								that.imageBase64=data.data
								that.signAgreement();
								// 这里的data.data就是canvas转换成的base64字符串
							},
							fail: function(err) {
								console.error('读取文件失败:', err);
							}
						});
					}
				});
			},
			signAgreement() {
				if (!this.name) {
					this.$tools.showToast('请输入姓名')
					return;
				}
				if (!this.idCar) {
					this.$tools.showToast('请输入身份证号')
					return;
				}
				if (!this.address) {
					this.$tools.showToast('请输入地址')
					return;
				}
				if (!this.imageBase64) {
					this.$tools.showToast('请签名')
					return;
				}
				this.$tools.loadIng('加载中..')
				this.$request.post(this.$api.signAgreement, {
					userId: uni.getStorageSync('userId'),
					storeId: this.storeId,
					orderId: this.holderOrderId,
					name: this.name,
					idCar: this.idCar,
					address: this.address,
					imageBase64: this.imageBase64
				}, {
					isJava: true
				}).then(res => {
					if (res.code == 200) {
						let {
							data = {}
						} = res;
						uni.hideLoading();
						this.isSign=true
						let pages = getCurrentPages(); //当前页
						let beforePage = pages[pages.length - 3]; //上个页面
						beforePage.$vm.pdfPath=data.pdfPath
						uni.navigateBack({delta:2})
					} else {
						this.$tools.showToast(res.message)
					}
				})
			},
			//保存到相册
			saveCanvasAsImg() {
				uni.canvasToTempFilePath({
					canvasId: 'handWriting',
					fileType: 'png',
					quality: 1, //图片质量
					success(res) {
						console.log(res.tempFilePath, 'canvas生成图片地址');
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已保存到相册',
									duration: 2000
								});
							}
						});
					}
				});
			},
			//预览
			previewCanvasImg() {
				uni.canvasToTempFilePath({
					canvasId: 'handWriting',
					fileType: 'jpg',
					quality: 1, //图片质量
					success(res) {
						uni.previewImage({
							urls: [res.tempFilePath] //预览图片 数组
						});
					}
				});
			},
			//设置canvas背景色  不设置  导出的canvas的背景为透明
			//@params：字符串  color
			setCanvasBg(color) {

				/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
				//rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
				//这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
				this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
				// ctx.setFillStyle('red')
				this.ctx.setFillStyle(color);
				this.ctx.fill(); //设置填充
				this.ctx.draw(); //开画
			}
		}
	};
</script>

<style lang="scss">
	.form-box {
		z-index: 999;
		padding: 44upx 28upx;
		.form-item {
			padding-bottom: 24upx;
			border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
			margin-bottom: 24upx;
			font-weight: 500;
			font-size: 26rpx;
			color: #FFFFFF;

			.form-title {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 26rpx;
				color: #FFFFFF;
				line-height: 30rpx;
				text-align: left;
				font-style: normal;
				text-transform: none;
				min-width: 104upx;
				margin-right: 40upx;
			}

			textarea {
				margin-top: 24upx;
				height: 90upx;
			}

			.placeholderClass {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 26rpx;
				color: rgba(255, 255, 255, 0.5);
				line-height: 30rpx;
				font-style: normal;
				text-transform: none;
			}
		}

		.tips {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color:#FFB726;
			line-height: 28rpx;
			font-style: normal;
			text-transform: none;
			margin-bottom: 24upx;
		}
		.clear{
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 26rpx;
			color: #FE5353;
			line-height: 30rpx;
			font-style: normal;
			text-transform: none;
		}
		.clear-btn {
			width: 256rpx;
			height: 96rpx;
			border-radius: 48rpx 48rpx 48rpx 48rpx;
			border: 1rpx solid rgba(255, 255, 255, 0.8);
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 34rpx;
			color: rgba(255, 255, 255, 0.8);
			line-height: 96rpx;
			text-align: center;
			font-style: normal;
			text-transform: none;
			margin-right: 14upx;
		}

		.handCenter {
			border: 1rpx solid #D1D2D3;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			flex: 5;
			overflow: hidden;
			box-sizing: border-box;
			margin-bottom: 24upx;
			height: 350upx;
			background: #FFFFFF;
			.handWriting {
				width: 100%;
				height: 100%;
			}
		}
	}

	.bottom-box {
		height: 140rpx;
		// background: #232428;
		// border-top: 1rpx solid #232428;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto;
		padding: 30upx 40upx;
		visibility: visible !important;
		z-index: 99999;

		.bottom-btn {
			height: 96rpx;
			line-height: 96rpx;
			background: linear-gradient(90deg, #598FFF 0%, #2662DE 100%);
			border-radius: 48rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 34rpx;
			color: #FFFFFF;
			line-height: 96rpx;
			text-align: center;
			font-style: normal;
			text-transform: none;
		}
	}
</style>